<template>
  <div style="padding-bottom: 10px">
    <el-line style="margin-bottom: 10px;" title="事项认领"></el-line>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item prop="keyWord" style="width: 100%;">
              <el-input
                  v-model="queryParams.matterName"
                  placeholder="事项名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                  suffix-icon="search"
                  :suffix-icon-click="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div>
              <el-button type="primary" icon="search" size="mini" @click="handleQuery">查询</el-button>
              <el-button icon="refresh" size="mini" @click="resetQuery">重置</el-button>
            </div>
          </el-col>
        </el-row>
    </el-form>
    <el-row type="flex" justify="space-between" align="middle">
      <el-col :span="24">
        <el-table v-loading="loading" :data="matterList" @selection-change="handleSelectionChange">
          <el-table-column min-width="3%" type="index" label="序号" align="center"/>
        <el-table-column  min-width="10%" label="事项名称" prop="matterName">
          <template #default="{ row }">
            <el-text type="primary" style="cursor: pointer" @click="getInto(row)">{{ row.matterName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column min-width="5%" label="当前进展" prop="workPrtKeyNode"/>
        <el-table-column min-width="6%" label="负责人" align="center" prop="matterResponsible"/>
        <el-table-column min-width="6%" label="关联人" align="center" prop="em2"/>
        <el-table-column min-width="8%" label="所属部门" align="center" prop="dept"/>
        <el-table-column min-width="6%" label="完成期限" align="center" prop="completionDeadline" :formatter="formatDate"/>
        <el-table-column min-width="5%" label="事项状态" align="center">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.em4"/>
          </template>
        </el-table-column>
          <el-table-column min-width="10%" label="批示意见" align="center" prop="dialogContent">
            <template #default="scope">
              <span v-html="scope.row.dialogContent"></span>
            </template>
          </el-table-column>
        <el-table-column min-width="5%" label="关注状态" align="center" prop="isFollowed">
          <template #default="scope">
            <el-tag v-if="scope.row.isFollowed" type="success">已关注</el-tag>
            <el-tag v-else type="info">未关注</el-tag>
          </template>
        </el-table-column>
          <el-table-column min-width="15%" label="操作" align="center">
            <template #default="scope">
                <el-button
                    :disabled="scope.row.em4 !== '2'"
                    :type="'primary'"
                    plain
                    @click="claim(scope.row)">
                  认领
                </el-button>
                <el-button
                           type="primary"
                           :disabled="scope.row.em4 !== '3'"
                           @click="createMatter(scope.row)">
                  维护事项
                </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script>
import {reactive, toRefs, ref, onMounted} from 'vue';
import {listTask, matterClaim,getMyMatterPage,dataScopeMatterList} from "@/api/matter/matter";
import {ElInput, ElSelect, ElOption, ElRow, ElCol, ElForm, ElFormItem, ElButton, ElMessageBox} from 'element-plus';
import useUserStore from "@/store/modules/user.js";


export default {
  name: "taskReception",
  components: {
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
    ElButton,
    ElMessageBox,
  },
  setup(_, {emit}) {
    const {proxy} = getCurrentInstance();
    const {task_status} = proxy.useDict('task_status');
    const userStore = useUserStore()
    const data = reactive({
      loading: false,
      task_status: task_status,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      matterList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        matterName: null,
        matterResponsibleId: userStore.id,

      },
      options1: [
        {value: '', label: '全部'},
        {value: '2', label: '待认领'},
        {value: '3', label: '进行中'},
      ],
      options2: [
        {value: '', label: '全部'},
        {value: '0', label: '超期'},
        {value: '1', label: '未超期'},
      ],
      form: {},
      rules: {
        matterResponsibleId: [
          {required: true, message: "事项负责人ID不能为空", trigger: "blur"},
        ],
      },
    });

    const getList = () => {
      data.loading = true;
      dataScopeMatterList(data.queryParams).then((response) => {
        data.matterList = response.rows;
        data.total = response.total;
        data.loading = false;
      });
    };
    const formatDate = (row, column, cellValue) => {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }


    const getStatusText = (row) => {
      if (row.em1) {
        return row.em1;
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        const summaryDate = row.summaryDate ? new Date(row.summaryDate) : null;

        if (summaryDate) {
          return summaryDate > deadlineDate ? '超时' : '完成';
        } else {
          return currentDate > deadlineDate ? '超时' : '进行中';
        }
      }
    };

    const getStatusColor = (row) => {
      if (row.em1) {
        return 'black';
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        const summaryDate = row.summaryDate ? new Date(row.summaryDate) : null;

        if (summaryDate) {
          return summaryDate > deadlineDate ? 'red' : 'green';
        } else {
          return currentDate > deadlineDate ? 'red' : 'blue';
        }
      }
    }
    const handleQuery = () => {
      data.queryParams.pageNum = 1;
      getList();
    };

    const resetQuery = () => {
      Object.assign(data.queryParams, {
        pageNum: 1,
        pageSize: 10,
        matterName: ''
      });
      handleQuery();
    };

    const handleSelectionChange = (selection) => {
      data.ids = selection.map((item) => item.matterId);
      data.single = selection.length !== 1;
      data.multiple = !selection.length;
    };

    // 根据任务状态返回认领按钮是否可点击
    const disableClaimButton = (taskStatus) => {
      if (taskStatus === '1') {
        return false; // 待认领状态，认领按钮可点击
      } else if (taskStatus == 1) {
        return true; // 已认领状态，认领按钮不可点击
      } else {
        return true; // 其他状态，认领按钮不可点击
      }
    };

    // 根据任务状态返回事项创建按钮是否可点击
    const disableCreateMatterButton = (taskStatus) => {
      if (taskStatus == 2 || taskStatus == 3) {
        return true; // 待认领状态或进行中状态，事项创建按钮不可点击
      } else {
        return false; // 其他状态，事项创建按钮可点击
      }
    };
    const handleCurrentChange = (currentPage) => {
      data.queryParams.pageNum = currentPage;
      getList();
    };

    const claim = (row) => {

      matterClaim({matterId: row.matterId,em4:'3'}).then(res => {
        getList();
        proxy.$modal.msgSuccess("事项认领成功");
      })

    };

    const createMatter = (row) => {
      emit('createMatter', row)

    };

    // 查看事项操作
    const viewMatter = (row) => {
      console.log('查看事项操作', row);
      emit('seeMatter', row)
    };


    onMounted(() => {
      getList();
    });

    return {
      ...toRefs(data),
      getList,
      handleQuery,
      resetQuery,
      handleSelectionChange,
      claim,
      createMatter,
      viewMatter,
      disableClaimButton,
      disableCreateMatterButton,
      handleCurrentChange,
      formatDate,
      getStatusText,
      getStatusColor,

    };
  },
};
</script>

<style>
</style>
